require "import"
import "android.media.AudioManager"
import "android.content.Context"
import "java.util.Locale"
import "android.widget.SeekBar"
import "android.widget.LinearLayout"
import "android.widget.Button"
import "com.androlua.LuaDialog"
import "android.widget.TextView"

local context = activity or service
if not context then return end

local audioManager = context.getSystemService(Context.AUDIO_SERVICE)
local lang = Locale.getDefault().getLanguage()

local strings = {
  ar = {
    title = "التحكم في المحرك",
    opt1 = "مستوى سرعة الكلام",
    opt2 = "مستوى صوت الكلام",
    opt3 = "مستوى حدة الصوت",
    accessibility = "استخدام صوت إمكانية الوصول",
    more = "المزيد",
    exit = "إغلاق",
    on = "مفعل (ON)",
    off = "معطل (OFF)",
    system_title = "التحكم في النظام",
    call = "مكالمة",
    ring = "نغمة الرنين",
    notification = "الإشعار",
    media = "الوسائط",
    alarm = "المنبه",
    creator = "Created by سايح فتحي"
  },
  en = {
    title = "Engine Control",
    opt1 = "Speech Rate Level",
    opt2 = "Speech Volume Level",
    opt3 = "Pitch Rate Level",
    accessibility = "Use Accessibility Volume",
    more = "More",
    exit = "Close",
    on = "ON",
    off = "OFF",
    system_title = "System Control",
    call = "Call",
    ring = "Ringtone",
    notification = "Notifications",
    media = "Media",
    alarm = "Alarm",
    creator = "Created by Sayah Fethi"
  }
}

local t = strings[lang] or strings["en"]

local function getJieshuoSettings()
  if service and service.getSharedPreferences then
    return service.getSharedPreferences("com.nirenr.talkman_preferences", Context.MODE_PRIVATE)
  end
  return nil
end

local prefs = getJieshuoSettings()

local function getEngineValue(config_key, fallback_val)
  if prefs then
    local val = prefs.getString(config_key, tostring(fallback_val))
    return tonumber(val) or fallback_val
  end
  return fallback_val
end

local function getAccessibityState()
  if prefs then
    return prefs.getBoolean("use_accessibility_volume", false)
  end
  return false
end

local engine_val1 = getEngineValue("tts_rate", 50)
local engine_val2 = getEngineValue("tts_volume", 50)
local engine_val3 = getEngineValue("tts_pitch", 50)
local is_acc_on = getAccessibityState()

local function applyEngineChanges(config_key, target_val)
  if prefs then
    prefs.edit().putString(config_key, tostring(target_val)).apply()
  end
end

local function forceEngineUpdate(speak_text)
  if service and service.click then
    service.click({{"%recreate%"}})
  end
  if service and service.postSpeak and speak_text then
    service.postSpeak(150, tostring(speak_text))
  end
end

local function toggleAccessibilityVolume()
  if prefs then
    is_acc_on = not is_acc_on
    prefs.edit().putBoolean("use_accessibility_volume", is_acc_on).apply()
    if service and service.click then
      service.click({{"%recreate%"}})
    end
    if accButton then
      local stateText = is_acc_on and t.on or t.off
      accButton.setText(t.accessibility .. " (" .. stateText .. ")")
    end
  end
end

local function openMoreVolumeDialog()
  local moreLayout = {
    LinearLayout,
    layout_width = "match_parent",
    layout_height = "match_parent",
    orientation = 1,
    {
      TextView,
      text = t.system_title,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      background = "#ff000000",
      textColor = "#f0f8ff",
      textSize = "25sp",
      gravity = "center",
    },
    {
      TextView,
      text = t.call,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      textColor = "#ffffff",
      textSize = "18sp",
      gravity = "center",
    },
    {
      SeekBar,
      id = "callSeekBar",
      layout_width = "match_parent",
      layout_height = "70dp",
      background = "#ff000000",
    },
    {
      TextView,
      text = t.ring,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      textColor = "#ffffff",
      textSize = "18sp",
      gravity = "center",
    },
    {
      SeekBar,
      id = "soundSeekBar",
      layout_width = "match_parent",
      layout_height = "70dp",
      background = "#ff000000",
    },
    {
      TextView,
      text = t.notification,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      textColor = "#ffffff",
      textSize = "18sp",
      gravity = "center",
    },
    {
      SeekBar,
      id = "notificationSeekBar",
      layout_width = "match_parent",
      layout_height = "70dp",
      background = "#ff000000",
    },
    {
      TextView,
      text = t.media,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      textColor = "#ffffff",
      textSize = "18sp",
      gravity = "center",
    },
    {
      SeekBar,
      id = "mediaSeekBar",
      layout_width = "match_parent",
      layout_height = "70dp",
      background = "#ff000000",
    },
    {
      TextView,
      text = t.alarm,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      textColor = "#ffffff",
      textSize = "18sp",
      gravity = "center",
    },
    {
      SeekBar,
      id = "alarmSeekBar",
      layout_width = "match_parent",
      layout_height = "70dp",
      background = "#ff000000",
    },
    {
      Button,
      text = t.exit,
      layout_width = "match_parent",
      layout_height = "wrap_content",
      textSize = "22sp",
      background = "#ffff0000",
      onClick = function()
        if moreDlg then moreDlg.dismiss() end
      end,
    }
  }

  moreDlg = LuaDialog()
  moreDlg.setView(loadlayout(moreLayout))
  moreDlg.show()

  local function setVolume(streamType, progress)
    audioManager.setStreamVolume(streamType, progress, 0)
  end

  local function initializeSeekBar(seekBar, streamType)
    local maxVolume = audioManager.getStreamMaxVolume(streamType)
    local currentVolume = audioManager.getStreamVolume(streamType)
    seekBar.setMax(maxVolume)
    seekBar.setProgress(currentVolume)
    seekBar.setOnSeekBarChangeListener(luajava.createProxy("android.widget.SeekBar$OnSeekBarChangeListener", {
      onProgressChanged = function(sb, progress, fromUser)
        if fromUser then setVolume(streamType, progress) end
      end,
      onStartTrackingTouch = function(sb) end,
      onStopTrackingTouch = function(sb) end,
    }))
  end

  initializeSeekBar(callSeekBar, AudioManager.STREAM_VOICE_CALL)
  initializeSeekBar(soundSeekBar, AudioManager.STREAM_RING)
  initializeSeekBar(notificationSeekBar, AudioManager.STREAM_NOTIFICATION)
  initializeSeekBar(mediaSeekBar, AudioManager.STREAM_MUSIC)
  initializeSeekBar(alarmSeekBar, AudioManager.STREAM_ALARM)
end

local layout = {
  LinearLayout,
  layout_width = "match_parent",
  layout_height = "match_parent",
  orientation = 1,
  {
    TextView,
    text = t.title,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    background = "#ff000000",
    textColor = "#f0f8ff",
    textSize = "25sp",
    gravity = "center",
  },
  {
    TextView,
    text = t.opt2,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textColor = "#ffffff",
    textSize = "18sp",
    gravity = "center",
  },
  {
    SeekBar,
    id = "engineSeekBar2",
    layout_width = "match_parent",
    layout_height = "70dp",
    background = "#ff000000",
  },
  {
    TextView,
    text = t.opt1,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textColor = "#ffffff",
    textSize = "18sp",
    gravity = "center",
  },
  {
    SeekBar,
    id = "engineSeekBar1",
    layout_width = "match_parent",
    layout_height = "70dp",
    background = "#ff000000",
  },
  {
    TextView,
    text = t.opt3,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textColor = "#ffffff",
    textSize = "18sp",
    gravity = "center",
  },
  {
    SeekBar,
    id = "engineSeekBar3",
    layout_width = "match_parent",
    layout_height = "70dp",
    background = "#ff000000",
  },
  {
    Button,
    id = "accButton",
    text = t.accessibility .. " (" .. (is_acc_on and t.on or t.off) .. ")",
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textSize = "22sp",
    background = "#ff555555",
    onClick = function()
      toggleAccessibilityVolume()
    end,
  },
  {
    Button,
    text = t.more,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textSize = "22sp",
    background = "#ff0000ff",
    onClick = function()
      openMoreVolumeDialog()
    end,
  },
  {
    TextView,
    text = t.creator,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textColor = "#aaaaaa",
    textSize = "16sp",
    gravity = "center",
    paddingTop = "10dp",
    paddingBottom = "10dp"
  },
  {
    Button,
    text = t.exit,
    layout_width = "match_parent",
    layout_height = "wrap_content",
    textSize = "22sp",
    background = "#ffff0000",
    onClick = function()
      if dlg then dlg.dismiss() end
    end,
  },
}

dlg = LuaDialog()
dlg.setView(loadlayout(layout))
dlg.show()

local function setupPercentSeekBar(seekBar, currentVal, configKey, saveCallback)
  seekBar.setMax(100)
  seekBar.setProgress(currentVal)
  seekBar.setOnSeekBarChangeListener(luajava.createProxy("android.widget.SeekBar$OnSeekBarChangeListener", {
    onProgressChanged = function(sb, progress, fromUser)
      if fromUser then 
        saveCallback(progress)
        applyEngineChanges(configKey, progress)
      end
    end,
    onStartTrackingTouch = function(sb) end,
    onStopTrackingTouch = function(sb)
      local progress = sb.getProgress()
      forceEngineUpdate(progress)
    end,
  }))
end

setupPercentSeekBar(engineSeekBar1, engine_val1, "tts_rate", function(val) engine_val1 = val end)
setupPercentSeekBar(engineSeekBar2, engine_val2, "tts_volume", function(val) engine_val2 = val end)
setupPercentSeekBar(engineSeekBar3, engine_val3, "tts_pitch", function(val) engine_val3 = val end)
